package com.eco.fanliapp.shengyaappeurekeclient;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eco.fanliapp.shengyaappeurekeclient.controller.LuceneController;
import com.eco.fanliapp.shengyaappeurekeclient.entity.AppGoods;
import com.eco.fanliapp.shengyaappeurekeclient.service.IAppGoodsService;
import com.eco.fanliapp.shengyaappeurekeclient.utils.LuceneUtil;
import com.github.pagehelper.util.StringUtil;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.*;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;
import org.wltea.analyzer.lucene.IKAnalyzer;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.math.BigDecimal;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.aliyun.openservices.shade.com.alibaba.rocketmq.common.UtilAll.deleteFile;

//
@Component
@Order(value = 1)
public class Runner implements CommandLineRunner {

    private static final Logger log = LoggerFactory.getLogger(Runner.class);
    @Autowired
    private LuceneUtil luceneUtil;
    @Autowired
    private IAppGoodsService appGoodsService;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void run(String... args) {
        log.info("创建索引开始....");
        redisTemplate.setKeySerializer(RedisSerializer.string());
        redisTemplate.setHashKeySerializer(RedisSerializer.string());
        redisTemplate.setHashValueSerializer(RedisSerializer.json());
        redisTemplate.setValueSerializer(RedisSerializer.json());
        try {
            String pathKey = "lucenePath";
            String key = "luceneIndex";
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String dateNowStr = sdf.format(new Date());
            String dir = "/home/nginx/fanli/lucene/index" + dateNowStr + "/";
            if (!redisTemplate.hasKey(pathKey)) {
                HashMap<String, String> newMap = new HashMap();
                newMap.put("newPath", dir);
                redisTemplate.opsForValue().set(pathKey, newMap);
            } else {
                Map<String, String> map = (Map) redisTemplate.opsForValue().get(pathKey);
                map.put("newPath", dir);
                redisTemplate.opsForValue().set(pathKey, map);
            }
            if (!redisTemplate.hasKey(key)) {
                Map map = new HashMap<>();
                map.put(dateNowStr, false);
                redisTemplate.opsForValue().set(key, map);
            } else {
                Map<String, Boolean> status = (Map) redisTemplate.opsForValue().get(key);
                status.put(dateNowStr, false);
                redisTemplate.opsForValue().set(key, status);
            }
//            Map<String, Boolean> status = (Map) redisTemplate.opsForValue().get(key);
//            for (String itemkey : status.keySet()) {
////                    if (!itemkey.equals(dateNowStr)) {
//                Map map = new HashMap<>();
//                map.put(dateNowStr, false);
//                redisTemplate.opsForValue().set(key, map);

            IndexReader indexReader = luceneUtil.getIndexReader(dir);
            IndexWriter indexWriter = luceneUtil.getIndexWriter(dir);

            for (int i = 0; i < indexWriter.maxDoc(); i++) {
                indexWriter.tryDeleteDocument(indexReader, i);
            }

            Page<AppGoods> page = new Page<>(1, 100000);
            QueryWrapper<AppGoods> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("item_top", 1).orderByDesc("update_time");
            IPage<AppGoods> appGoodsIPage = appGoodsService.page(page, queryWrapper);

            if (appGoodsIPage != null && appGoodsIPage.getRecords() != null) {
                for (AppGoods appGoods : appGoodsIPage.getRecords()) {
                    List list = new ArrayList<>();
                    list.add(appGoods);
                    BigDecimal price = (BigDecimal) appGoodsService.getPrice(null, list);
                    //创建Document对象
                    Document doc = new Document();
                    //获取每列数据
                    Field itemid = new Field("itemid", appGoods.getItemid() == null ? "" : appGoods.getItemid(), TextField.TYPE_STORED);
                    Field itemtitle = new Field("itemtitle", appGoods.getItemtitle() == null ? "" : appGoods.getItemtitle(), StringField.TYPE_STORED);
                    Field itemshorttitle = new Field("itemshorttitle", appGoods.getItemshorttitle() == null ? "" : appGoods.getItemshorttitle(), StringField.TYPE_STORED);
                    Field itemdesc = new Field("itemdesc", appGoods.getItemdesc() == null ? "" : appGoods.getItemdesc(), StringField.TYPE_STORED);
                    Field itemObject = new Field("itemObject", JSON.toJSONString(appGoods), TextField.TYPE_STORED);


                    Field fqcat = new Field("fqcat", appGoods.getFqcat() == null ? "" : appGoods.getFqcat(), StringField.TYPE_STORED);
                    Field recommend = new Field("recommend", appGoods.getRecommend() == null ? "" : appGoods.getRecommend().toString(), StringField.TYPE_STORED);
                    Field itemTop = new Field("itemTop", appGoods.getItemTop() == null ? "" : appGoods.getItemTop().toString(), StringField.TYPE_STORED);


                    //销量
                    Field itemsales = new FloatPoint("total_sales", (float) (appGoods.getItemsale() == null ? 0 : appGoods.getItemsale()));
                    //价格  到手价
                    Field itemprice = new FloatPoint("price", (price == null ? 0 : price).floatValue());
                    // 综合 更新时间
                    Field updateTime = new FloatPoint("tk_total_commi", (appGoods.getUpdateTime() == null ? 0 : appGoods.getUpdateTime().getTime()));
                    // Field updateTime = new Field("tk_total_commi", DateTools.dateToString(appGoods.getUpdateTime(),DateTools.Resolution.DAY), StringField.TYPE_STORED);
                    //最省钱 优惠卷加联盟返佣
                    BigDecimal commiCoupon = new BigDecimal(appGoods.getTkmoney() == null ? "0" : appGoods.getTkmoney()).add(new BigDecimal(appGoods.getCouponmoney()));
                    Field itemCheaper = new FloatPoint("tk_rate", Float.valueOf(commiCoupon.toString() == null ? "0" : commiCoupon.toString()));

                    if (price == null || price.intValue() == 0) {
                        luceneUtil.deleteIndex(appGoods.getItemid(), dir);
                        continue;
                    }
                    //销量
                    doc.add(new FloatDocValuesField("total_sales", (float) (appGoods.getItemsale() == null ? 0 : appGoods.getItemsale()) * 1000F));
                    doc.add(new StoredField("total_sales", (float) (appGoods.getItemsale() == null ? 0 : appGoods.getItemsale())));
                    //价格
                    doc.add(new StoredField("price", (price == null ? 0 : price).floatValue()));//存储
                    doc.add(new FloatDocValuesField("price", ((price == null ? 0 : price).floatValue() * 1000F)));//排序
                    //优惠卷加联盟返佣
                    doc.add(new FloatDocValuesField("tk_rate", Float.valueOf(commiCoupon.toString() == null ? "0" : commiCoupon.toString()) * 1000F));
                    doc.add(new StoredField("tk_rate", Float.valueOf(commiCoupon.toString() == null ? "0" : commiCoupon.toString())));

                    doc.add(new FloatDocValuesField("tk_total_commi", (appGoods.getUpdateTime() == null ? 0 : appGoods.getUpdateTime().getTime())));
                    doc.add(new StoredField("tk_total_commi", (appGoods.getUpdateTime() == null ? 0 : appGoods.getUpdateTime().getTime())));

                    doc.add(itemid);
                    doc.add(itemtitle);
                    doc.add(itemshorttitle);
                    doc.add(itemdesc);
                    doc.add(itemObject);
                    doc.add(itemsales);
                    doc.add(itemprice);
                    doc.add(itemCheaper);
                    doc.add(updateTime);
                    doc.add(fqcat);
                    doc.add(recommend);
                    doc.add(itemTop);

                    luceneUtil.deleteIndex(appGoods.getItemid(), dir);
                    if (price == null || price.intValue() == 0) {
                        continue;
                    }
                    luceneUtil.write(doc, dir);
                }
                log.info("创建索引结束");
            } else {
                log.info("没有获取到商品信息");
            }
//                    }
//                    log.info("今天已经更新");
//                    return;
//            }
//            }
            if (redisTemplate.hasKey(pathKey)) {
                Map<String, String> status = (Map) redisTemplate.opsForValue().get(pathKey);
                delFile(status.get("oldPath"));
            }
            HashMap oldMap = new HashMap();
            oldMap.put("oldPath", dir);
            redisTemplate.opsForValue().set(pathKey, oldMap);
            Map map = new HashMap<>();
            map.put(dateNowStr, true);
            redisTemplate.opsForValue().set(key, map);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("结束创建索引  0 * */1 * * ?");
        }
    }

    public Boolean delFile(String dir) {
        boolean delete_flag = false;
        if (!StringUtil.isEmpty(dir)) {
            File file = new File(dir);
            if (file.exists()) {
                if (file.isFile()) {
                    delete_flag = file.delete();
                } else {
                    for (File files : file.listFiles()) {
                        deleteFile(files);
                    }
                    delete_flag = file.delete();
                }
            } else {
                delete_flag = false;
            }
        }
        return delete_flag;
    }


}